<script setup lang="ts">
import { reactive, ref } from "vue";

const list = ref([
  { id: 1, name: "《红楼梦》", author: "曹雪芹" },
  { id: 2, name: "《西游记》", author: "吴承恩" },
  { id: 3, name: "《水浒传》", author: "施耐庵" },
  { id: 4, name: "《三国演义》", author: "罗贯中" },
]);

// 根据id删除数据
const delData = (id: number) => {
  // filter不影响原数组
  list.value = list.value.filter((item) => item.id !== id);
};

const bookInfo = reactive({
  id: 0,
  name: "",
  author: "",
});

const addBook = () => {
  bookInfo.id = Date.now();
  bookInfo.name = `《${bookInfo.name}》`;

  // 要重新拷贝一下
  // list.value.push({
  //   id: bookInfo.id,
  //   name: bookInfo.name,
  //   author: bookInfo.author,
  // });

  // 合并对象(浅拷贝):把一个或者多个源对象中的属性复制到目标对象，并返回修改后的目标对象。
  // list.value.push(Object.assign({}, bookInfo))
  
  list.value.push({...bookInfo}) 

  bookInfo.name = "";
  bookInfo.author = "";
};
</script>

<template>
  <div id="app">
    <h3>黑马书架</h3>
    <div>
      <input type="text" v-model="bookInfo.name" placeholder="请输入书名" />
      <input type="text" v-model="bookInfo.author" placeholder="请输入作者" />
      <button @click="addBook">添加</button>
      <p>{{ bookInfo }}</p>
    </div>
    <ol>
      <li v-for="(item, index) in list" :key="item.id">
        <span>{{ item.name }}</span>
        <span>{{ item.author }}</span>
        <span>{{ item.id }}</span>
        <button @click="delData(item.id)">删除</button>
      </li>
    </ol>
  </div>
</template>
